<?php

namespace Home\Controller;

class OrderController extends CommonController
{
    /**
     *订单列表首页
     */
    public function index()
    {
        $id = $_SESSION['customer']['id'];
        $address = $this->address->where("customer_id = '$id'")->find();

        //第一种方法：查出用户要购买的商品信息
        $total = 0;
        $carts = $this->cart->where("customer_id = '$id'")->select();
        foreach ($carts as &$cart) {
            $cart['product'] = $this->product->where("id = '$cart[product_id]'")->find();
            $total += floatval($cart['product']['price']) * intval($cart['num']);
        }
        //第二种方法：查出用户要购买的商品信息
//        $products = $this->cart->alias('a')->field('a.id as cart_id,a.num,b.*')
//            ->join('product as b ON b.id=a.product_id', 'LEFT')
//            ->where(['a.customer_id' => $customer_id])->select();
//        $total = 0;
//        foreach($products as $k=>$v){
//            $total += floatval($v['price']) * intval($v['num']);
//        }
        $this->assign(compact('carts', 'address', 'total'));
        $this->display();
    }

    /**
     * 新增收货地址
     */
    public function order_address()
    {
        if (IS_AJAX) {
            $data['customer_id'] = $_SESSION['customer']['id'];
            $data['name'] = I('post.name');
            $data['tel'] = I('post.tel');
            $data['area'] = I('post.area');
            $data['address'] = I('post.address');

            $info = array('status' => 1, 'msg' => '新增地址成功');
            if (strlen($data['name']) < 5 || strlen($data['name']) > 20) {
                $info = array('status' => 0, 'msg' => '用户名的长度必须在5-20之间');
            }
            $mobile = '/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$/';
            if (!preg_match($mobile, $data['tel'])) {
                $info = array('status' => 0, 'msg' => '手机号格式不正确');
            }

            if ($info['status'] == 1) {
                $address = $this->address->where("customer_id = '$data[customer_id]'")->save($data);
                if (!$address) {
                    $this->address->where("customer_id = '$data[customer_id]'")->add($data);
                }
            }
            $this->ajaxReturn($info);
        }
    }

    /**
     * 我要下单
     */
    public function store()
    {
        $customer_id = $_SESSION['customer']['id'];
        //连表（a:cart表；b：product表）查出商品信息
        $products = $this->cart->alias('a')
            ->field('a.id as cart_id,a.num,b.*')
            ->join('product as b ON b.id=a.product_id', 'LEFT')
            ->where(['a.customer_id' => $customer_id])->select();

        $total = 0;
        foreach ($products as $k => $v) {
            $total += floatval($v['price']) * intval($v['num']);

            //判断商品库存
            if (intval($v['num']) > intval($v['stock'])) {
                $info = array('status' => 0, 'msg' => '此商品库存不足');
            }
        }

        //判断购物车商品是否提交
        $cart = $this->cart->where("customer_id = '$customer_id'")->find();
        if (!$cart) {
            $info = array('status'=>0,'msg'=>'此订单已提交');
            $this->ajaxReturn($info);
        }

        //生成订单
        $data['customer_id'] = $customer_id;
        $data['order_no'] = make_token_code();
        $data['created_at'] = time();
        $data['total_price'] = $total;
        $data['address_id'] = I('post.address_id');
        $data['status'] = 1;  //初始状态为1
        //订单数据插入订单表
        $id = $this->order->add($data);
        if ($id) {
            $orderProductInfo['order_id'] = $id;

            //插入订单商品表的数据
            foreach ($products as $k => $v) {
                $orderProductInfo['product_id'] = $v['id'];
                $orderProductInfo['number'] = $v['num'];
                $this->order_product->add($orderProductInfo);
            }

            //支付成功后对应减去商品的库存及清空购物车
            $numbers = intval($orderProductInfo['number']);
            $product_id = $orderProductInfo['product_id'];
            $this->product->where("id = '$product_id'")->setField('sale_done', $numbers);  //已售商品数量
            $this->product->where("id = '$product_id'")->setDec('stock', $numbers);  //减去库存
            $this->cart->where("customer_id = $customer_id")->delete();  //清空购物车
            $info = array('status' => 1, 'msg' => '您已成功下单');
            $info['id'] = $id;
        } else {
            $info = array('status' => 0, 'msg' => '下单失败');
        }
        $this->ajaxReturn($info);
    }

    /**
     * 我要下单页面
     */
    public function confirm()
    {
        $id = I('get.id');
        //查出地址
        $order = $this->order->where("id = $id")->find();
        $address = $this->address->where("id = $order[address_id]")->find();

        //查出购买商品
        $order_products = $this->order_product->where("order_id = $id")->select();
        foreach ($order_products as &$order_product) {
            $order_product['product'] = $this->product->where("id= $order_product[product_id]")->find();
        }

        $this->assign(compact('order', 'address', 'order_products'));
        $this->display();
    }

}